package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class dishController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        Page<Dish> dishPage = new Page<Dish>(page, pageSize);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.like(name != null && name != "", Dish::getName, name);
        //按照降序排序
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage, dishLambdaQueryWrapper);
        Page<DishDTO> dishDTOPage = new Page<DishDTO>();
        //dishDTOPage.setTotal(dishPage.getTotal());
        //dish dishdto对拷
        BeanUtils.copyProperties(dishPage, dishDTOPage, "records");
        List<DishDTO> dishDTOList = dishPage.getRecords().stream().map(dish -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(dish, dishDTO);
            Category category = categoryService.getById(dish.getCategoryId());
            dishDTO.setCategoryName(category.getName());
            if (category != null) {
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }
            return dishDTO;
        }).collect(Collectors.toList());

        dishDTOPage.setRecords(dishDTOList);
        return R.success(dishDTOPage);
    }


    @PostMapping
    @Transactional
    public R save(@RequestBody DishDTO dishDTO) {
        log.info("save dishDTO:{}", dishDTO);
        dishService.save(dishDTO);

        Long dishId = dishDTO.getId();
        List<DishFlavor> flavors1 = dishDTO.getFlavors();
        List<DishFlavor> dishFlavors = flavors1.stream().map(item->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavors);

        //清空redis中缓存数据
        Long categoryId = dishDTO.getCategoryId();
        redisTemplate.delete("dish-"+categoryId);
//        List<DishFlavor> flavors = dishDTO.getFlavors();
//
//        if (flavors != null && flavors.size() > 0) {
//            //获取菜品id
//            //保存菜品的口味数据
//            Long id = dishDTO.getId();
//            for (DishFlavor flavor : flavors) {
//                flavor.setDishId(id);
//                dishFlavorService.save(flavor);
//            }
//        }
        return R.success("添加菜品成功");
    }

    //更新
    @GetMapping("/{id}")
    public R getDish(@PathVariable Long id) {
        DishDTO dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }


    //修改
    @PutMapping
    public R<String> queryOne(@RequestBody DishDTO dishDTO) {
        //修改dish表中指定字段

        //删除dish关联的口味表中当前菜品口味
        dishService.updateById(dishDTO);
        Long id = dishDTO.getId();
        List<DishFlavor> flavors1 = dishDTO.getFlavors();
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        dishFlavorService.remove(queryWrapper);
        List<DishFlavor> dishFlavors = flavors1.stream().map(item->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(dishFlavors);
        Long categoryId = dishDTO.getCategoryId();
        redisTemplate.delete("dish-"+categoryId);


//        dishFlavorService.removeById(id);
//
//        //批量添加此次请求的口味列表数据
//        List<DishFlavor> flavors = dishDTO.getFlavors();
//        for (DishFlavor flavor : flavors) {
//            flavor.setDishId(id);
//            dishFlavorService.save(flavor);
//        }
        return R.success("修改成功");

    }


    @DeleteMapping
    public R queryOne(@RequestParam List ids) {
        log.info(ids.toString());
        dishService.removeByIds(ids);
        LambdaUpdateWrapper<DishFlavor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(updateWrapper);
        redisTemplate.delete("*");
        return R.success("删除成功");
    }

    //修改状态
    @PostMapping("/status/{status}")
    public R changeStatus(@RequestBody List ids , @PathVariable Integer status) {
        LambdaUpdateWrapper<Dish> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(Dish::getStatus,status);
        lambdaUpdateWrapper.in(Dish::getId, ids);
        dishService.update(lambdaUpdateWrapper);
        redisTemplate.delete("*");
        return R.success("变更成功");
    }

    //查询菜品
    @GetMapping("/list")
    public R<List<DishDTO>> list(Dish dish){

        List<DishDTO> dishDTOLists = (List<DishDTO>) redisTemplate.opsForValue().get("dish-" + dish.getCategoryId());
        //redis中缓存了
        if(dishDTOLists!=null){
            return R.success(dishDTOLists);
        }
        //redis中没有缓存

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        //排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        List<DishDTO> dishDTOList = list.stream().map((item)->{
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item,dishDTO);
            Long id = item.getCategoryId();
            Category category = categoryService.getById(id);
            if (category!=null) {
                String name = category.getName();
            dishDTO.setCategoryName(name);
            }
            Long id1 = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,id1);
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            dishDTO.setFlavors(list1);
            return dishDTO;


        }).collect(Collectors.toList());

        //将mysql中的数据缓存到redis中
        redisTemplate.opsForValue().set("dish-" + dish.getCategoryId(),dishDTOLists);
        return R.success(dishDTOList);
    }

}
